<template>
  <div class="app-main-container">
    <div class="app-main-title">
      团体会员开通
      <div class="goback" @click="goBack">
        <i class="el-icon-refresh-left" /> 返回上一页
      </div>
    </div>
    <el-form ref="ruleForm" class="doumee-form" :model="param" :rules="rules" label-width="150px" label-suffix="：">
      <div class="property-title">团体信息</div>
      <el-form-item label="团体名称" prop="name">
        <el-input v-model="param.name" type="text" placeholder="请输入团体名称" maxlength="20" class="w400" />
      </el-form-item>
      <el-form-item label="团体类型" prop="type">
        <el-input v-model="param.type" type="text" placeholder="请输入团体类型(例如：民营企业、事业单位、国企等)" maxlength="20" class="w400" />
      </el-form-item>
      <el-form-item label="团体地址">
        <el-input v-model="param.addr" type="text" placeholder="请输入团体地址" maxlength="20" class="w400" />
      </el-form-item>
      <el-form-item label="营业执照" prop="yyzzUrl">
        <transition name="fade">
          <Cropper
            v-if="dialogCropperVisible"
            :option-img="optionImg"
            :fileinfo="fileinfo"
            :fixed-number="[32, 32]"
            use-type="MEMBER_IMG"
            @formSubmit="cropperSubmit"
            @formClose="cropperClose"
          />
        </transition>
        <el-upload
          class="device-uploader"
          :action="uploadFileUrl"
          :data="uploadData"
          :show-file-list="false"
          accept=".pdf,.jpg,.png"
          :on-change="addFileChange"
          :auto-upload="false"
        >
          <i class="el-icon-plus uploader-icon" />
          <div v-show="param.yyzzUrl" class="file" :style="'background-image: url(' + param.yyzzUrl + ')'">
            <div class="delete">
              <i class="el-icon-delete icon" @click.stop="deleteYyzzImage" />
            </div>
          </div>
        </el-upload>
      </el-form-item>
      <div class="line-style" />
      <div class="property-title">签约信息</div>
      <el-form-item label="签约金额" prop="amot">
        <el-input v-model="param.amot" placeholder="请输入签约金额" class="w400" oninput="value=value.replace(/[^\d.]/g, '').replace(/\.{2,}/g, '.').replace('.', '$#$').replace(/\./g, '').replace('$#$', '.').replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3').replace(/^\./g, '')" />
      </el-form-item>
      <el-form-item label="合同附件" prop="configPicture">
        <transition name="fade">
          <Cropper
            v-if="dialogCropperVisible2"
            :option-img="optionImg"
            :fileinfo="fileinfo"
            :fixed-number="[32, 32]"
            use-type="MEMBER_IMG"
            @formSubmit="cropperSubmit2"
            @formClose="cropperClose"
          />
        </transition>
        <el-upload
          class="device-uploader"
          :action="uploadFileUrl"
          :data="uploadData"
          :show-file-list="false"
          accept="image"
          :on-change="addFileChange2"
          :auto-upload="false"
        >
          <i class="el-icon-plus uploader-icon" />
          <div v-show="param.hturl" class="file" :style="'background-image: url(' + param.hturl + ')'">
            <div class="delete">
              <i class="el-icon-delete icon" @click.stop="deleteHtImage" />
            </div>
          </div>
        </el-upload>
      </el-form-item>
      <el-form-item label="会员卡">
        <div class="cart_list">
          <div
            v-for="(item, index) in vipTypes"
            :key="index"
            :class="[index == vipType ? 'select-style' : 'normal-style']"
            class="card-style"
            @click="selectCard(index)"
          >
            <img :src="item.showAvatar" alt="">
            <div class="card-name">{{ item.cardName }}</div>
            <span class="card-first-price">￥{{ item.price }}</span>
          </div>
        </div>

      </el-form-item>
      <div class="line-style" />
      <div class="property-title">管理员信息</div>
      <el-form-item v-if="!this.$route.query.courseId" label="是否已开通会员">
        <div class="member_open">
          <el-radio v-model="radio" label="1">是</el-radio>
          <el-radio v-model="radio" label="2">否</el-radio>
        </div>
      </el-form-item>
      <div v-if="radio == '1'" class="isMember">
        <el-form-item label="会员卡号">
          <div class="w400">
            <el-input
              v-model="cardNum"
              placeholder="请输卡号/手机号"
              class="input-with-select bottom-speace-style"
              @keyup.enter.native="searchAction"
            >
              <el-button slot="append" icon="el-icon-search" @click="searchAction" />
            </el-input>
            <div v-if="showMessage" class="card-message">
              <div class="first-line">
                <span class="message-title-style">NO.</span>
                <span class="message-value-style">{{ cardMessage.number }}</span>
                <span class="message-value-style">{{ cardMessage.nickName }}</span>
                <span v-if="cardMessage.cardName" class="card-name-style">{{ cardMessage.cardName }}</span>
                <button class="message-title-style close-style" @click="closeMessage">x</button>
              </div>
              <div class="first-line">
                <span class="message-title-style">手机：</span>
                <span class="message-value-style">{{ cardMessage.phone }}</span>
                <span class="message-title-style">充值金额：</span>
                <span class="message-value-style">{{ cardMessage.remainingMoney ? cardMessage.remainingMoney : 0 }}</span>
                <span class="message-title-style">赠送金额：</span>
                <span class="message-value-style">{{ cardMessage.remainingGiveMoney ? cardMessage.remainingGiveMoney : 0
                }}</span>
                <!-- <span class="message-title-style">余额：</span>
                <span class="message-value-style">{{ cardMessage.money }}</span> -->
                <!-- <span class="message-title-style">赠送：</span>
                <span class="message-value-style">{{ cardMessage.totalConsume }}</span> -->
              </div>
            </div>
          </div>
        </el-form-item>
      </div>
      <div v-else-if="radio == '2'" class="isNotMember">
        <el-form-item label="手机号" prop="adminPhone">
          <el-input
            v-model="param.adminPhone"
            class="code-style"
            type="text"
            onkeyup="value=value.replace(/[^\d^]/g,'')"
            placeholder="请输入手机号"
          />
          <el-button class="code-btn-style" type="primary" :loading="loding" :disabled="codeDsiabled" @click="getCode">{{
            codeBtnText }}</el-button>
        </el-form-item>
        <el-form-item label="验证码" prop="vcode">
          <el-input v-model="param.vcode" type="text" onkeyup="value=value.replace(/[^\d^]/g,'')" placeholder="请输入验证码" />
        </el-form-item>
        <el-form-item label="姓名" prop="adminName">
          <el-input v-model="param.adminName" type="text" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-radio v-model="param.sex" label="1">男</el-radio>
          <el-radio v-model="param.sex" label="2">女</el-radio>
        </el-form-item>
        <el-form-item label="人脸采集" prop="showFaceUrl">
          <img :src="param.showFaceUrl ? param.showFaceUrl : faceimg" class="face-image" alt="" @click="acquisitionFace">
        </el-form-item>
        <el-form-item label="身份证号" prop="identityNumber">
          <el-input
            v-model="param.identityNumber"
            type="text"
            onkeyup="value=value.replace(/[^\X0-9]/g, '')"
            oninput="if(value.length>18)value=value.slice(0,18)"
            placeholder="请输身份证号码"
          />
        </el-form-item>
        <el-form-item label="实体卡号" prop="entityNumber">
          <el-input v-model="param.entityNumber" class="entitycard-style" placeholder="请输入实体卡号" />
          <el-button class="entitycard-btn-style" type="primary" :loading="loding" @click="getCardNum">采集实体卡</el-button>
        </el-form-item>
        <el-form-item label="新密码" prop="password">
          <el-input v-model="param.password" placeholder="请输入新密码" type="password" auto-complete="new-password" />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input v-model="param.confirmPassword" placeholder="请确认密码" type="password" auto-complete="new-password" />
        </el-form-item>
      </div>
      <el-form-item>
        <el-button type="primary" :loading="loadingb" @click="onSubmit()">提交</el-button>
      </el-form-item>
    </el-form>
    <orderDialog ref="child" @orderSuccess="$router.replace({ name: 'GroupList' })" />
  </div>
</template>

<script>
import {
  uploadFile,
  cardList,
  VIPInfo,
  sendSMS,
  creatTeam,
  collectCard,
  collectFace
} from '@/api'
import store from '@/store'
import Cropper from '@/components/cropper'
import orderDialog from '@/components/order'
export default {
  name: 'GroupOpen',
  components: {
    Cropper, orderDialog
  },
  data() {
    const equalToPassword = (rule, value, callback) => {
      if (this.param.password !== value) {
        callback(new Error('两次输入的密码不一致'))
      } else {
        callback()
      }
    }
    return {
      modalDialog: store.getters.dialog,
      dialogCropperVisible: false,
      dialogCropperVisible2: false,
      optionImg: '',
      files: {},
      fileinfo: {},
      radio: '1',
      teamId: '',
      mainTitle: '团体会员开通',
      loding: false,
      isRenew: false,
      codeBtnText: '获取验证码',
      time: 60,
      codeDsiabled: false,
      uploadFileUrl: uploadFile,
      loading: false,
      loadingb: false,
      pickerOptions: {
        disabledDate(time) {
          return (
            time.getTime() < new Date(new Date().toLocaleDateString()).getTime()
          )
        }
      },
      uploadData: {
        folder: 'MEMBER_IMG',
        type: ''
      },
      venueId: sessionStorage.getItem('venueId'),
      param: {},
      rules: {
        name: [{ required: true, message: '请输入团体名称', trigger: 'blur' }],
        type: [{ required: true, message: '请输入团体类型', trigger: 'blur' }],
        addr: [{ required: true, message: '请输入团体地址', trigger: 'blur' }],
        // yyzzUrl: [
        //   { required: true, message: '请上传营业执照', trigger: 'change' }
        // ],
        amot: [
          {
            pattern: /^(([1-9][0-9]*)|(([0]\.\d{1,2}|[1-9][0-9]*\.\d{1,2})))$/,
            required: true,
            message: '请输入签约金额(元),最多保留2位小数',
            trigger: 'blur'
          }
        ],
        adminPhone: [{ required: true, message: '请输入管理员手机号', trigger: 'blur' }],
        vcode: [{ required: true, message: '请输入验证码', trigger: 'blur' }],
        adminName: [{ required: true, message: '请输入管理员姓名', trigger: 'blur' }],
        sex: [
          { required: true, message: '请选择管理员性别', trigger: 'change' }
        ],
        identityNumber: [
          { required: true, message: '请输入身份证号', trigger: 'blur' },
          {
            required: true,
            pattern:
              /^(([1-9][0-9]{5}(19|20)[0-9]{2}((0[1-9])|(1[0-2]))([0-2][1-9]|10|20|30|31)[0-9]{3}([0-9]|X|x))|([1-9][0-9]{5}[0-9]{2}((0[1-9])|(1[0-2]))([0-2][1-9]|10|20|30|31)[0-9]{3}))$/,
            message: '请输入正确的身份证号',
            trigger: 'blur'
          }
        ],
        // showFaceUrl: [
        //   { required: true, message: '请采集人脸', trigger: 'blur' }
        // ],
        password: [
          { required: true, message: '新密码不能为空', trigger: 'blur' },
          {
            min: 6,
            max: 20,
            message: '长度在 6 到 20 个字符',
            trigger: 'blur'
          }
        ],
        confirmPassword: [
          { required: true, message: '确认密码不能为空', trigger: 'blur' },
          {
            min: 6,
            max: 20,
            message: '长度在 6 到 20 个字符',
            trigger: 'blur'
          },
          { required: true, validator: equalToPassword, trigger: 'blur' }
        ]
      },
      vipTypes: [],
      vipType: '',
      cardNum: '',
      cardMessage: {},
      showMessage: false,
      edit: false,
      faceimg: require('@/icons/png/default_faceid.png')
    }
  },
  created() {
    // this.meta = this.$route.meta.buttons || []
  },
  mounted() {
    if (this.$route.query.id && !this.$route.query.isRenew) {
      this.teamId = this.$route.query.id
      this.isRenew = this.$route.query.isRenew
      this.$route.meta.title = '编辑团体会员'
      this.mainTitle = '编辑团体会员'
      this.edit = true
    } else if (this.$route.query.id && this.$route.query.isRenew) {
      this.teamId = this.$route.query.id
      this.isRenew = this.$route.query.isRenew
      this.$route.meta.title = '续签团体会员'
      this.mainTitle = '续签团体会员'
      this.edit = true
    } else {
      this.$route.meta.title = '团体会员开通'
    }
    this.getCardList()
  },
  methods: {
    goBack() {
      this.$router.go(-1)
    },
    closeMessage() {
      this.cardNum = ''
      this.cardMessage = {}
      this.showMessage = false
    },
    getCode() {
      if (this.param.adminPhone.length !== 11) {
        this.$message.error('请输入正确的手机号')
        return
      }
      sendSMS({ param: { phone: this.param.adminPhone, type: '01' }})
        .then((res) => {
          // console.log(res)
          if (res.errorCode === '000000') {
            setTimeout(() => {
              this.codeDsiabled = true
              this.codeBtnText = '(60)重新发送'
              this.time = 60
              const timeInterval = setInterval(() => {
                this.time--
                this.codeBtnText = '(' + this.time + ')' + '重新发送'
                if (this.time === 0) {
                  clearInterval(timeInterval)
                  this.codeBtnText = '重新发送'
                  this.codeDsiabled = false
                  // console.log('结束')
                }
              }, 1000)
            }, 1000)
          }
        })
        .catch((err) => {
          console.log(err)
        })
    },
    selectCard(index) {
      this.vipType = index
      this.$set(this.param, 'cardType', this.vipTypes[index].id)
    },
    searchAction() {
      // console.log('搜索会员卡')
      if (!this.cardNum.length) {
        this.$message.error('请输卡号/手机号')
        return
      }
      VIPInfo({
        param: {
          phoneOrNo: this.cardNum
        }
      })
        .then((res) => {
          // console.log(res)
          if (res.errorCode === '000000') {
            this.cardMessage = res.record
            this.showMessage = true
            this.$set(this.param, 'adminId', this.cardMessage.id)
          }
        })
        .catch((err) => {
          console.log(err)
          this.cardMessage = {}
          this.showMessage = false
          this.$set(this.param, 'adminId', '')
        })
    },
    getCardList() {
      // 获取卡类型列表
      cardList({
        param: {
          cardName: null,
          isnormal: null,
          channel: null
          // type: '1'
        }
      })
        .then((res) => {
          // console.log(res)
          if (res.errorCode === '000000') {
            // this.vipTypes = res.recordList
            res.recordList.forEach(item => {
              if (item.isnormal !== '1' && item.channel !== '1_0') {
                this.vipTypes.push(item)
              }
            })
            this.$set(this.param, 'cardType', this.vipTypes[0].id)
            // console.log(this.vipTypes)
          }
        })
        .catch((err) => {
          console.log(err)
        })
    },
    // 上传合同图片成功
    htUploadSuccess(res, file, fileList) {
      if (res.success) {
        this.$set(this.param, 'hturl', res.showUrl)
        this.$set(this.param, 'htUrl', res.insertUrl)
        this.$refs.ruleForm.clearValidate()
      } else {
        this.$message.error(res.msg || '上传失败')
      }
    },
    // 裁剪确定按钮
    cropperSubmit2(config) {
      // preImg 完整路径  urlPre 不包含域名
      if (config.success) {
        this.$set(this.param, 'hturl', config.showUrl)
        this.$set(this.param, 'htUrl', config.insertUrl)
        this.dialogCropperVisible2 = false
        this.$refs.ruleForm.clearValidate()
      } else {
        this.$message.error(config.msg || '上传失败')
        this.dialogCropperVisible2 = false
      }
    },
    // 上传图片，开始裁剪
    async addFileChange2(file) {
      // 上传，拿到file文件
      this.files = file.raw
      this.$nextTick(() => {
        this.optionImg = URL.createObjectURL(file.raw)
        this.fileinfo = file.raw
        this.dialogCropperVisible2 = true
      })
    },
    // 删除已上传合同
    deleteHtImage() {
      this.$set(this.param, 'htUrl', '')
      this.$set(this.param, 'hturl', '')
    },

    // 上传营业执照成功
    yyzzUploadSuccess(res, file, fileList) {
      if (res.success) {
        this.$set(this.param, 'yyzzUrl', res.showUrl)
        this.$set(this.param, 'yyzz', res.insertUrl)
        this.$refs.ruleForm.clearValidate()
      } else {
        this.$message.error(res.msg || '上传失败')
      }
    },
    // 上传图片，开始裁剪
    async addFileChange(file) {
      // 上传，拿到file文件
      this.files = file.raw
      this.$nextTick(() => {
        this.optionImg = URL.createObjectURL(file.raw)
        this.fileinfo = file.raw
        this.dialogCropperVisible = true
      })
    },
    // 裁剪确定按钮
    cropperSubmit(config) {
      // preImg 完整路径  urlPre 不包含域名
      if (config.success) {
        this.$set(this.param, 'yyzzUrl', config.showUrl)
        this.$set(this.param, 'yyzz', config.insertUrl)
        this.dialogCropperVisible = false
        this.$refs.ruleForm.clearValidate()
      } else {
        this.$message.error(config.msg || '上传失败')
        this.dialogCropperVisible = false
      }
    },
    // 裁剪取消
    cropperClose() {
      this.dialogCropperVisible = false
      this.dialogCropperVisible2 = false
    },
    // 删除已上传营业执照
    deleteYyzzImage() {
      this.$set(this.param, 'yyzzUrl', '')
      this.$set(this.param, 'yyzz', '')
    },
    onSubmit() {
      if (this.radio === '1' && !this.cardMessage.id) {
        this.$message.warning('请输卡号/手机号并搜索会员')
        return
      }
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          this.loadingb = true
          this.param.venueId = this.venueId
          const param = { ...this.param }
          if (this.radio === '2') {
            param.adminId = ''
          }
          creatTeam({
            param
          })
            .then((res) => {
              this.loadingb = false
              if (res.errorCode === '000000') {
                this.$message.success('提交成功')
                const obj = {
                  ...res.record,
                  allPrice: res.record.money
                }
                this.$refs.child.continuePay(obj, 'groupOpen')
              }
            })
            .catch((err) => {
              this.loadingb = false
              console.log(err)
            })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    getCardNum() {
      this.loading = true
      collectCard({
        param: {
          venueId: sessionStorage.getItem('venueId'),
          shopId: sessionStorage.getItem('shopId')
        }
      })
        .then(res => {
          this.loading = false
          if (res.errorCode === '000000') {
            this.$set(this.param, 'entityNumber', res.record.card)
          }
        })
    },
    acquisitionFace() {
      collectFace({
        param: {
          venueId: sessionStorage.getItem('venueId'),
          shopId: sessionStorage.getItem('shopId')
        }
      })
        .then(res => {
          // console.log('详情', res)
          if (res.errorCode === '000000') {
            this.$set(this.param, 'faceUrl', res.record.insertUrl)
            this.$set(this.param, 'showFaceUrl', res.record.showUrl)
          }
        })
    }
  }
}
</script>

<style lang="scss" scoped>
@import "@/styles/variables.scss";

.code-style {
  width: 70%;
}

.code-btn-style {
  margin-left: 20px;
}

.device-uploader {
  width: 80px;
  height: 80px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #fff;
  cursor: pointer;
  border: 1px dashed #ccc;
  border-radius: 8px;
  transition: all 0.3s;
  margin-right: 20px;

  &:hover {
    border-color: $menuActive;

    .uploader-icon {
      color: $menuActive;
    }
  }

  ::v-deep .el-upload {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    position: relative;

    .file {
      width: 100%;
      height: 100%;
      position: absolute;
      top: 0;
      left: 0;
      background-size: contain;
      background-position: center;
      background-repeat: no-repeat;
      border-radius: 8px;
      display: flex;
      align-items: center;
      justify-content: center;

      .delete {
        background-color: rgba(0, 0, 0, 0.5);
        position: absolute;
        width: 100%;
        height: 100%;
        top: 0;
        left: 0;
        display: none;
        align-items: center;
        justify-content: center;

        .icon {
          color: #fff;
        }
      }

      &:hover {
        .delete {
          display: flex;
        }
      }
    }
  }

  .uploader-icon {
    color: #aaaaaa;
    font-size: 22px;
    transition: all 0.3s;
  }
}

.line-style {
  margin-bottom: 20px;
}

.device-uploaders {
  ::v-deep .el-upload-list__item {
    width: 80px;
    height: 80px;
  }

  ::v-deep .el-upload {
    width: 80px;
    height: 80px;
    line-height: 80px;
  }
}

.card-style {
  width: 158px;
  height: 160px;
  background: #FFFFFF;
  border-radius: 2px;
  border: 1px solid #D8D8D8;
  margin-right: 10px;
  margin-bottom: 10px;
  padding: 12px;
  line-height: 16px;
  cursor: pointer;
  img {
    width: 134px;
    height: 80px;
    display: flex;
    margin-bottom: 12px;
  }
  .card-name {
    color: #222;
    font-weight: 500;
    line-height: 18px;
    margin-bottom: 10px;
  }
}
.cart_list{
  display: flex;
  flex-wrap: wrap;
}
.select-style {
  border: solid 1px $primaryColor;
}
.card-message {
  margin-top: 10px;
  background-color: #f2f2f2;
  height: 60px;
  line-height: 20px;

  .first-line {
    height: 30px;
    padding: 5px;

    .message-title-style {
      color: #999;
    }

    .card-name-style {
      display: inline-block;
      border: 1px #999 solid;
      border-radius: 4px;
      background-color: #fff;
      font-size: 12px;
      padding-left: 5px;
      padding-right: 5px;
      height: 20px;
      text-align: center;
    }

    .close-style {
      font-size: 20px;
      float: right;
      margin-right: 5px;
      margin-top: -2px;
      padding: 0;
      border: 0px #999 solid;
    }

    .message-value-style {
      margin-right: 15px;
      color: #222;
    }
  }
}

.pay-style {
  width: 110px;
  height: 30px;
  font-size: 15px;
  line-height: 1px;
  vertical-align: middle
}

.slelect-pay-style {
  background-color: #1943A9;
  color: #fff;
}

.normal-pay-style {
  border: 1px solid #d8d8d8;
  background-color: #fff;
  color: #222;
}

.messgae-style {
  color: #DD0707;
}

.price-style {
  font-size: 17px;
  font-weight: 500;
}

.unit-style {
  margin-right: 20px;
}

.bottom-speace-style {
  margin-bottom: 10px;
}

.card-message {
  margin-bottom: 10px;
  background-color: #f2f2f2;
  height: 60px;
  line-height: 20px;

  .first-line {
    height: 30px;
    padding: 5px;

    .message-title-style {
      color: #999;
    }

    .card-name-style {
      display: inline-block;
      border: 1px #999 solid;
      border-radius: 4px;
      background-color: #fff;
      font-size: 12px;
      padding-left: 5px;
      padding-right: 5px;
      height: 20px;
      text-align: center;
    }

    .close-style {
      font-size: 20px;
      float: right;
      margin-right: 5px;
      margin-top: -2px;
      padding: 0;
      border: 0px #999 solid;
    }

    .message-value-style {
      margin-right: 15px;
      color: #222;
    }
  }
}

.footer-style {
  display: flex;
  justify-content: space-between;
  background-color: #f2f2f2;
  margin: -10px -20px -30px;
  height: 50px;

  .bottom-left {
    margin-left: 20px;
    height: 20px;
    margin-top: 15px;

    .sum-title-style {
      font-size: 15px;
      color: #222;
    }

    .sum-pay-value-style {
      font-size: 17px;
      font-weight: 500;
      color: #DD0707;
    }

    .dis-title-style {
      font-size: 14px;
      color: #222;
    }

    .discoun-style {
      font-size: 16px;
      color: #DD0707;
    }
  }

  .bottom-right {
    margin-right: 20px;
    margin-top: 10px;
    height: 30px;

    .pay-action-style {
      width: 100px;
      height: 30px;
      font-size: 15px;
      line-height: 1px;
      vertical-align: middle
    }
  }
}
</style>
